import { defineConfig } from "vite";
import monkey, { util, cdn } from "vite-plugin-monkey";
import AutoImport from "unplugin-auto-import/vite";

export default defineConfig({
  build: {
    target: "es2020",
  },
  plugins: [
    AutoImport({
      imports: [util.unimportPreset],
    }),
    monkey({
      userscript: {
        connect: "*",
        author: "Feny",
        version: "1.1.1",
        match: ["*://*/*"],
        name: "JSON Viewer",
        license: "GPL-3.0-only",
        homepage: "https://github.com/xFeny/UserScript/tree/main/monkey-jsonviewer",
        icon: "",
        namespace: "http://tampermonkey.net/",
        description:
          "格式化显示 JSON 使数据看起来更加漂亮。支持 JSON 主题色切换。支持 JSON 脑图，清晰明了的查看 JSON 层级。支持通过 JSON Crack 查看 JSON。支持手动输入 JSON，HTTP 请求获取 JSON",
      },
      entry: "src/main.js",
      build: {
        systemjs: "inline",
        externalGlobals: {
          jsmind: cdn.unpkg("jsmind", "es6/jsmind.js").concat(util.dataUrl(";window.jsmind=jsMind;")),
          "dom-to-image": ["domtoimage", () => `https://unpkg.com/dom-to-image@2.6.0/src/dom-to-image.js`].concat(
            util.dataUrl(";window.domtoimage=domtoimage;")
          ),
          beautifier: cdn
            .unpkg("beautifier")
            .concat(
              util.dataUrl(";window.beautifier=js_beautify;window.js_beautify=js_beautify;window.css_beautify=css_beautify;")
            ),
          "highlight.js": ["hljs", () => `https://unpkg.com/@highlightjs/cdn-assets@11.10.0/highlight.min.js`].concat(
            util.dataUrl(";window.hljs=hljs;")
          ),
        },
        cssSideEffects: () => {
          return (e) => {
            // 是否向document.head插入样式
            window.addEventListener("message", (event) => {
              const { data } = event;
              if (!data?.addStyle) return;
              if (typeof GM_addStyle === "function") return GM_addStyle(e);
              const o = document.createElement("style");
              o.textContent = e;
              document.head.append(o);
            });
          };
        },
      },
    }),
  ],
});
